package org.i_plus.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.i_plus.model.BlogBean;
import org.i_plus.model.Blog_ReplyBean;
import org.i_plus.model.MemberBean;
import org.i_plus.model.dao.BlogDAOHibernate;
import org.i_plus.model.dao.MemberDAOHibernate;
import org.i_plus.model.services.BlogReplyService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class BlogReplyServlet extends HttpServlet {
	private BlogReplyService service;
	private BlogDAOHibernate dao;
	private MemberDAOHibernate mdao;
	@Override
	public void init() throws ServletException {
		ServletContext application = this.getServletContext();
		ApplicationContext context=
				WebApplicationContextUtils.getWebApplicationContext(application);
		this.service = (BlogReplyService)context.getBean("blog_ReplyService");
		this.dao = (BlogDAOHibernate)context.getBean("BlogDAO");
		this.mdao = (MemberDAOHibernate)context.getBean("MemberDAO");
		super.init();
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//接收
			//String buttonck=req.getParameter("replybutton");
			//System.out.println("buttonck:" +buttonck);
			String recontent =req.getParameter("content");
			System.out.println("recontent:" +recontent);
			String bnumtemp = req.getParameter("id");
			System.out.println("id:" +bnumtemp);
			String account=req.getParameter("account");
			System.out.println("account:" +account);
			
		//驗證
			Map<String,String> errors=new HashMap<String,String>();
			req.setAttribute("errors", errors);
			
			
		//轉換
			int bnum = 0;
			if(bnumtemp!=null && bnumtemp.length()!=0){
				bnum=Integer.parseInt(bnumtemp);
			}
		//dispatch
			Blog_ReplyBean reply=new Blog_ReplyBean();
			BlogBean blog = new BlogBean();
			MemberBean member = new MemberBean();
			
			reply.setRe_B_content(recontent);
			blog.setB_num(bnum);
			reply.setBlogBean(blog);
			member.setAccount(account);
			reply.setMemberBean(member);
			service.insertRe(reply);
			
//			if(buttonck!=null && buttonck.length()!=0){
//				Blog_ReplyBean insertresult = null;
//				if(buttonck.equals("送出")){
//					 insertresult=service.insertRe(reply);
//				}req.setAttribute("reinsert", insertresult);
//			}
			req.getRequestDispatcher("/View/IamMember.jsp").forward(req, resp);
//				System.out.println("insertresult:" + service.insertRe(reply));
			return ;
		
		
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
	
	
}
